const Database = require('better-sqlite3'),
    path = require('path'),
    dbRelate = path.join(__dirname, '/app.db'),
    db = new Database(dbRelate),
    { cryptoPwd } = require('../utils/MD5')


// 插入新用户
const password = 'ddd'; // 这是您想要为用户设置的密码
const hashedPassword = cryptoPwd(password);

const zsExists = db.prepare('SELECT COUNT(*) AS count FROM users WHERE username = ?').get('zs');

if (zsExists.count === 0) {
    // 'admin' 用户不存在，可以插入
    const insertUser = db.prepare(`
      INSERT INTO users (username, password) VALUES (?, ?)
    `);
    const info = insertUser.run('zs', hashedPassword);
}



const lsExists = db.prepare('SELECT COUNT(*) AS count FROM users WHERE username = ?').get('ls');

if (lsExists.count === 0) {
    // 'admin' 用户不存在，可以插入
    const insertUser = db.prepare(`
      INSERT INTO users (username, password) VALUES (?, ?)
    `);
    const info = insertUser.run('ls', hashedPassword);
    
}

const getAllUsers = () => db.prepare('select * from users').all()

const checkUser = (username, password) => {
    try {
        const row = db.prepare('select * from users where username = ? ').get(username)
        if (row) {
            if (row.password === cryptoPwd(password)) {
                return { status: 0, id: row.id, message: '登录成功' }
            } else {
                return { status: 1, message: '密码错误' }
            }
        } else {
            return { status: 1, message: '用户不存在' }
        }
    } catch (error) {
        return { status: 1, message: error.message }
    }
}

//注册逻辑
const addUser = (username, password) => {
    try {
        const row = db.prepare('select * from users where username = ? ').get(username)
        if (row) {
            return { status: 1, message: '注册失败, 用户名已被占用' };
        } else {
            password = cryptoPwd(password)
            db.prepare('insert into users(username,password) values(?,?)')
              .run(username, password);
            return { status: 0, message: '注册成功!' };
        }
    } catch (error) {
        return { status: 1, message: error.message }
    }
}

module.exports = {
    getAllUsers,
    checkUser,
    addUser
}